# -*- coding: utf-8 -*-
# @Time : 2023/4/21 9:03
# @Author : 陈鹏飞
# @Email ： 2578925789@qq.com
# @File : jsonConvert
# @Description : 将yolov8-val输出的json转换为统一格式用于调用pycocotools。

import os
import json

def convertJson():
    val_json = "/home/chenpengfei/dataset/DSM_Dataset_class4_20220211_fukang/val/val.json"
    json_file = "./runs/detect/val4/predictions.json"
    json_new_file = "./runs/detect/val4/predictions_new.json"

    img_id_dict = {}

    with open(val_json, "r", encoding="utf-8") as f1:
        json_content1 = json.load(f1)
        for imgInfo in json_content1["images"]:
            img_id_dict[imgInfo["file_name"].split(".")[0]] = imgInfo["id"]

    with open(json_file, "r", encoding="utf-8") as f2:
        json_content2 = json.load(f2)
        for i, item in enumerate(json_content2):
            json_content2[i]["image_id"] = int(img_id_dict[item["image_id"]])
            json_content2[i]["category_id"] = int(item["category_id"] + 1)

        json_content2 = sorted(json_content2, key=lambda x: x["image_id"])  # 重新排序
        with open(json_new_file, "w", encoding="utf-8") as f3:
            json.dump(json_content2, f3, indent=4, ensure_ascii=True)

def readJson():
    json_new_file = "./runs/detect/val4/predictions_new.json"
    # json_new_file = "./runs/detect/train/cocoval/pred_pt_result.json"
    with open(json_new_file, "r", encoding="utf-8") as f:
        json_content = json.load(f)
        num_objects = len(json_content)
        print("num_objects:{}".format(num_objects))

if __name__ == "__main__":
    readJson()
    # convertJson()
